<template>
  <div class="wrapper">
    <div class="header">
      <el-image :src="logo" class="logo"></el-image>
      korubo控制台
    </div>
    <div class="login">
      <div style="margin: 20px 0; text-align: center; font-size: 24px"><b>登 录</b></div>
      <el-form :model="user" :rules="rules" ref="userForm">
        <el-form-item prop="name">
          <el-input size="medium" prefix-icon="el-icon-user" v-model="user.name"></el-input>
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input size="medium" prefix-icon="el-icon-lock" show-password v-model="user.pwd"></el-input>
        </el-form-item>

        <el-form-item style="text-align: center">
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>

export default {
  name: "Login",
  data() {
    return {
      logo: require("@/assets/logo.png"),
      user: {},
      // 图片验证码
      // 验证码规则
      rules: {
        name: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        pwd: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    login() {
      this.$refs['userForm'].validate(async (valid) => {
        if (valid) {
          try {
            const res = await this.request.post("/user/login", this.user)
            if (res.code === 200) {
              await this.$store.dispatch('auth/login', {
                user: res.data.user,
                menus: res.data.menus,
                token: res.data.token
              })

              // 获取重定向地址
              const redirect = this.$route.query.redirect || '/home'
              this.$router.push(redirect)
              this.$message.success("登录成功")
            } else {
              this.$message.error(res.msg)
            }
          } catch (error) {
            console.log(error)
            this.$message.error("登录失败，请重试")
          }
        }
      })
    },
  }
}
</script>

<style>
.logo {
  width: 56px;
  height: 53px;
}
.header {
  margin-left: 37%;
  padding-top: 7%;
  padding-right: 10%;
  height: 60px;
  line-height: 60px;
  font-size: 25px;
  padding-left: 50px;
  color: white;
}

.login {
  margin: 17% 0px 0px 65%;
  width: 250px;
  color: white;
}

.wrapper {
  background-image: url('../assets/bg.png');
  background-repeat: no-repeat;
  background-size: cover;
  min-height: 100vh;
}
</style>
